package 力扣;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZhuYi
 * @create 2025/4/7 19:58
 */
public class 组合总和有重复_LCR082 {
    public static void main(String[] args) {
        int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        System.out.println(combinationSum2(candidates, target).toString());
    }

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        int start = 0;
        Arrays.sort(candidates);
        backtrack(new ArrayList<Integer>(), candidates, target, 0, res);
        return res;
    }

    static void backtrack(List<Integer> state, int[] candidates, int target, int start, List<List<Integer>> res) {
        if (target == 0) {
            res.add(new ArrayList<Integer>(state));
            return;
        }
        // 剪枝二：从 start 开始遍历，避免生成重复子集
        // 剪枝三：从 start 开始遍历，避免重复选择同一元素
        for (int i = start; i < candidates.length; i++) {
            // 剪枝一：若子集和超过 target ，则直接结束循环
            // 这是因为数组已排序，后边元素更大，子集和一定超过 target
            if (target - candidates[i] < 0) {
                break;
            }
            // 剪枝四：如果该元素与左边元素相等，说明该搜索分支重复，直接跳过
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            state.add(candidates[i]);
            backtrack(state, candidates, target - candidates[i], i + 1, res);
            state.remove(state.size() - 1);
        }
    }
}
